package me.leiusual.sharing.repository

import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations.switchMap
import androidx.paging.Config
import androidx.paging.PagedList
import androidx.paging.toLiveData
import io.reactivex.Single
import me.leiusual.sharing.api.ApiSharing
import me.leiusual.sharing.api.model.Withdraw
import me.leiusual.sharing.api.model.WithdrawCreate
import me.leiusual.sharing.repository.datasource.WithdrawDataSourceFactory
import me.leiusual.sharing.repository.model.Data
import javax.inject.Inject
import javax.inject.Singleton

/**
 * author: leiusual
 * create on: 2019-08-01
 * description:
 */
@Singleton
class WithdrawRepository @Inject constructor(
    private val apiSharing: ApiSharing
) {

  fun withdrawAccount(): Single<Map<String, String>> {
    return apiSharing.withdrawAccount()
  }

  fun withdrawCreate(request: WithdrawCreate.Request): Single<Unit> {
    return apiSharing.withdrawCreate(request)
  }

  fun withdrawApply(wcId: Long): Single<Unit> {
    return apiSharing.withdrawApply(wcId)
  }

  fun withdrawCancel(wcId: Long): Single<Unit> {
    return apiSharing.withdrawCancel(wcId)
  }

  fun withdrawDelete(wcId: Long): Single<Unit> {
    return apiSharing.withdrawDelete(wcId)
  }

  fun withdrawQuery(storeId: Long): WithDrawQueryListing {
    val factory = WithdrawDataSourceFactory(apiSharing, storeId)
    val loadInitial = switchMap(factory.withdrawDataSource) { it.loadInitial }
    val pagedList = factory.toLiveData(Config(9, initialLoadSizeHint = 9))
    return WithDrawQueryListing(loadInitial, pagedList)
  }

  data class WithDrawQueryListing(
      val loadInitial: LiveData<Data<Unit>>,
      val pagedList: LiveData<PagedList<Withdraw>>
  )
}